<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        var depts = [
            { id: 1, pid: "", name: "aaa" },
            { id: 2, pid: 1, name: "bbb" },
            { id: 3, pid: 1, name: "ccc" },
            { id: 5, pid: "", name: "eee" },
            { id: 6, pid: 2, name: "fff" },
        ];
        // const arr1 = []
        // depts.forEach((item1) => {
        //     if (item1.pid === '') {
        //         arr1.push(item1)
        //         const arr2 = []
        //         depts.forEach((item2) => {
        //             if (item2.pid === item1.id) {
        //                 arr2.push(item2)
        //                 const arr3 = []
        //                 depts.forEach((item3) => {
        //                     if (item3.pid === item2.id) {
        //                         arr3.push(item3)
        //                     }
        //                 })
        //                 if (arr3.length > 0) {
        //                     item2.children = arr3
        //                 }
        //             }
        //         }
        //         )
        //         if (arr2.length > 0) {
        //             item1.children = arr2
        //         }
        //     }
        // })
        // console.log(arr1)

        function fn (pid) {
            const arr = []
            depts.forEach((item) => {
                if (item.pid === pid) {
                    arr.push(item)
                    const arr1 = fn(item.id)
                    if (arr1.length > 0) {
                        item.children = arr1
                    }
                }
            })
            return arr
        }
        console.log(fn('')); 
    </script>
</body>

</html>